package com.jinghao.tws.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.jinghao.core.common.exception.JingHaoCustomerException;
import com.jinghao.core.common.service.impl.JingHaoBaseServiceImpl;
import com.jinghao.core.common.util.JhHttpClientUtil;
import com.jinghao.core.common.util.cnd.IJhSql.ORDER;
import com.jinghao.core.common.util.cnd.JhCnd;
import com.jinghao.core.common.util.cnd.JhUpdate;
import com.jinghao.sys.entity.SysAccount;
import com.jinghao.sys.service.ISysAccountService;
import com.jinghao.tws.entity.WvAccessConfig;
import com.jinghao.tws.entity.WvAutoVedioConfig;
import com.jinghao.tws.entity.WvCloudAccessConfig;
import com.jinghao.tws.entity.WvPallet;
import com.jinghao.tws.entity.WvPallet.EWvPallet;
import com.jinghao.tws.entity.WvProcess;
import com.jinghao.tws.entity.WvProcess.EWvProcess;
import com.jinghao.tws.entity.WvProcessConfig;
import com.jinghao.tws.entity.WvProcessMergeConfig;
import com.jinghao.tws.entity.WvProduct;
import com.jinghao.tws.entity.WvProduct.EWvProduct;
import com.jinghao.tws.entity.WvTaskInfo;
import com.jinghao.tws.entity.WvTaskInfo.EWvTaskInfo;
import com.jinghao.tws.entity.WvUploadTaskInfo;
import com.jinghao.tws.entity.WvUploadTaskInfo.EWvUploadTaskInfo;
import com.jinghao.tws.service.IWvAccessConfigService;
import com.jinghao.tws.service.IWvAutoVedioConfigService;
import com.jinghao.tws.service.IWvFlowService;
import com.jinghao.tws.service.IWvPalletService;
import com.jinghao.tws.service.IWvProcessConfigService;
import com.jinghao.tws.service.IWvProcessMergeConfigService;
import com.jinghao.tws.service.IWvProcessService;
import com.jinghao.tws.service.IWvProductService;
import com.jinghao.tws.service.IWvPublicSynchronousService;
import com.jinghao.tws.service.IWvTaskInfoService;
import com.jinghao.tws.service.IWvUploadTaskInfoService;
import com.jinghao.tws.util.EJhTwsCode;

@Service("wvPalletService")
public class WvPalletServiceImpl extends JingHaoBaseServiceImpl<WvPallet> implements IWvPalletService {
	//==================定制内容开始======================
//在这里修改代码
	
	@Resource
	private IWvProductService wvProductService;
	
	@Resource
	private IWvProcessService wvProcessService;
	
	
	@Resource
	private ISysAccountService sysAccountService;
	
	@Resource
	private IWvFlowService wvFlowService;
	
	@Resource
	private IWvProcessConfigService wvProcessConfigService;
	
	@Resource
	private IWvAutoVedioConfigService wvAutoVedioConfigService;
	
	@Resource
	private IWvProcessMergeConfigService wvProcessMergeConfigService;
	
	@Resource
	private IWvTaskInfoService wvTaskInfoService;
	
	@Resource
	private IWvUploadTaskInfoService wvUploadTaskInfoService;
	
	@Resource
	private IWvAccessConfigService wvAccessConfigService;
	
	@Resource
	private IWvPalletService wvPalletService;
	
	@Resource
	private IWvPublicSynchronousService wvPublicSynchronousService;
	
	@Override
	public void addWmsInfo(Map<String,Object> map) {
		if(map!=null){
			this.logger.info("托盘信息："+JSON.toJSONString(map));
			//第一步：检查用户是否登录
			this.checkUserIsLoginInfo(map);
			
			//第二步：检查流程是否存在
			 if(map.get("flowId")==null||StringUtils.isEmpty(map.get("flowId").toString())||map.get("flowId").toString().equals("null")){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供流程流程编码信息（字段：flowId）！");
			 }
			String _UUID= this.wvFlowService.checkWvFlowIsExists(map.get("flowId").toString());
			if(_UUID==null){
				throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"提供流程编码信息有误！（字段：flowId）");
			}
			
			//第三步：检查托盘数据信息
			WvPallet model=new WvPallet();
			model.setPalletUuid(model.getUUID());
			model.setCreateTime(new Date());
			model.setFlowCode(map.get("flowId").toString());
			this.checkWvPalletInfo(map, model);
			
			//第四步：检查环节业务数据信息
			List<WvProcess> vList=new ArrayList<WvProcess>();
			this.checkWvProcessInfo(map, vList,model);
			String _locationId="";
			for(WvProcess tempModel:vList){
				if(tempModel.getFprocessId().equals("tallying")){
					_locationId=tempModel.getLocationId();
					break;
				}
			}
			
			//第五步：检查产品信息
			List<WvProduct> pList=new ArrayList<WvProduct>();
			this.checkWvProductInfo(map, pList,model,_locationId);
			
			//第六步：保存数据
			model.setUploadStatus(EWvPallet.uploadStatus_1.getKey());
			model.setFileUploadStatus(EWvPallet.fileUploadStatus_0.getKey());
			
			this.add(model);
			for(WvProduct wProduct:pList){
				this.wvProductService.add(wProduct);
			}
			for(WvProcess wProcess:vList){
				this.wvProcessService.add(wProcess);
			}
			
			//第七步：根据数据生成视频任务信息
            this.addWvTaskInfo(vList,model,pList,_UUID);
            
            //第八步：提示清理数据
            pList.clear();
            vList.clear();
            map.clear();
			
		}else{
			throw new JingHaoCustomerException("9999","请求有误，请提供相关数据！");
		}
	}
	
	public void addWvTaskInfo(List<WvProcess> vList,WvPallet wvPallet,List<WvProduct>  pList,String flowUuid){
		//a:根据配置信息是否自动生成视频 信息
		 WvAutoVedioConfig wvAutoVedioConfig=new WvAutoVedioConfig();
		 wvAutoVedioConfig.setFlowCode(wvPallet.getFlowCode());
		 wvAutoVedioConfig.setFlowUuid(flowUuid);
		 this.wvAutoVedioConfigService.listAllWvAutoVedioConfig(wvAutoVedioConfig);
		 List<String> processCodeList=new ArrayList();
		 List<Map<String,Object>> list=wvAutoVedioConfig.getMapList();
		 String cType=null, processCode=null;
		 
		 //把需要生成视频的数据合并在一个集合中
		 for(Map<String,Object> map:list){
			 cType=map.get("ctype")!=null?map.get("ctype").toString():null;
			 processCode=map.get("processCode")!=null?map.get("processCode").toString():"";
			 if(cType!=null&&cType.equals("1")&&processCode!=null){
				 processCodeList.add(processCode);
			 }
		 }
		 Date fromDate=null,toDate=null;
		 String mediaInfo="";
		 boolean hasMegerProcess=false;
		 WvTaskInfo wvTaskInfo=null;
		 WvProcessConfig wvProcessConfig=new WvProcessConfig();
		 wvProcessConfig.setFcode(wvPallet.getFlowCode());
		 JhCnd cnd=new JhCnd();
		 cnd.andEquals("fcode");
		 cnd.orderBy("w.sort", "asc");
		 wvProcessConfig.setJhCnd(cnd);
		 wvProcessConfig.setPage(null);
		 List<Map<String,Object>> processConfigList=this.wvProcessConfigService.queryMapListById(wvProcessConfig, "listMapListProcessconfigByFlowCode");
		 //生成短损任务
		 List<Map<String,Object>> mediaInfolist=null;
		 List<List<Map<String,Object>>> megerMediaInfolist=null;
		 Map<String,Object> dataMap=null;
		 if(processCodeList.contains("demageProcess")){
			  for(WvProduct wvProduct:pList){
				  if(wvProduct.getStatus().equals(EWvProduct.status_1.getKey())){
					  mediaInfolist=new ArrayList<Map<String,Object>>();
					  for(Map<String,Object> map:processConfigList){
						  if(map.get("locationId")!=null&&map.get("locationId").toString().equals(wvProduct.getLocationId())&&map.get("processId").toString().equals("tally-event")){
							  dataMap=new HashMap<String,Object>();
							  dataMap.put("deviceId", Integer.parseInt(map.get("deviceId").toString()));
							  dataMap.put("channelId",Integer.parseInt(map.get("channelId").toString()));
							  fromDate=new Date();
							  fromDate.setTime(wvProduct.getCheckTime().getTime()-2*60*1000);
							  dataMap.put("from",fromDate.getTime());
							  toDate=new Date();;
							  toDate.setTime(wvProduct.getCheckTime().getTime()+2*60*1000);
							  dataMap.put("to",toDate.getTime());
							  mediaInfolist.add(dataMap);
						  }
					  }
					  mediaInfo=this.wvProductService.getMediaInfoByList(mediaInfolist);
					  //生成任务信息
				      wvTaskInfo=new WvTaskInfo();
					  wvTaskInfo.setTaskUuid(wvTaskInfo.getUUID());
					  wvTaskInfo.setType(EWvTaskInfo.type_3.getKey());
					  wvTaskInfo.setFpalletId(wvPallet.getPalletId());
					  wvTaskInfo.setFpalletUuid(wvPallet.getPalletUuid());
					  wvTaskInfo.setFproductUuid(wvProduct.getProductUuid());
					  wvTaskInfo.setVideoStatus(EWvTaskInfo.videoStatus_1.getKey());
					  wvTaskInfo.setCreateTime(new Date());
					  wvTaskInfo.setLastCheckTime(new Date());
					  wvTaskInfo.setMedioInfo(mediaInfo);
					  this.wvTaskInfoService.add(wvTaskInfo);
				  }
			  }
		 }
		 List<String> mergeList=new ArrayList();
		 if(processCodeList.contains("megerProcess")){
			 WvProcessMergeConfig wvProcessMerge=new WvProcessMergeConfig();
			 wvProcessMerge.setFlowUuid(flowUuid);
			 wvProcessMergeConfigService.listAllWvProcessMergeConfig(wvProcessMerge);
			 List<Map<String,Object>> listMerge=wvProcessMerge.getMapList();
			 hasMegerProcess=true;
		     for(Map<String,Object> map:listMerge){
		    	 mergeList.add(map.get("processCode").toString());
		     }
		     megerMediaInfolist=new ArrayList<List<Map<String,Object>>>();
		 }
		 
		 List<WvProcess> mergeProcessList=new ArrayList<WvProcess>();
		 //生成环节视频任务 
		 for(WvProcess wProcess:vList){
			 if(processCodeList.contains(wProcess.getFprocessId())){
				  mediaInfolist=new ArrayList<Map<String,Object>>();
				  for(Map<String,Object> map:processConfigList){
					  if(map.get("locationId")!=null&&map.get("locationId").toString().equals(wProcess.getLocationId())&&!map.get("processId").toString().equals("tally-event")){
						  dataMap=new HashMap<String,Object>();
						  dataMap.put("deviceId", Integer.parseInt(map.get("deviceId").toString()));
						  dataMap.put("channelId",Integer.parseInt(map.get("channelId").toString()));
						  dataMap.put("from",wProcess.getStartTime().getTime());
						  dataMap.put("to",wProcess.getEndTime().getTime());
						  mediaInfolist.add(dataMap);
					  }
				  }
				 mediaInfo=this.wvProductService.getMediaInfoByList(mediaInfolist);
				 wvTaskInfo=new WvTaskInfo();
				 wvTaskInfo.setTaskUuid(wvTaskInfo.getUUID());
				 wvTaskInfo.setType(EWvTaskInfo.type_1.getKey());
				 wvTaskInfo.setFpalletId(wvPallet.getPalletId());
				 wvTaskInfo.setFpalletUuid(wvPallet.getPalletUuid());
				 wvTaskInfo.setFprocessId(wProcess.getFprocessId());
				 wvTaskInfo.setFprocessUuid(wProcess.getProcessUuid());
				 wvTaskInfo.setVideoStatus(EWvTaskInfo.videoStatus_1.getKey());
				 wvTaskInfo.setCreateTime(new Date());
				 wvTaskInfo.setLastCheckTime(new Date());
				 wvTaskInfo.setMedioInfo(mediaInfo);
				 this.wvTaskInfoService.add(wvTaskInfo);
				 
				 if(mergeList.contains(wProcess.getFprocessId())&&hasMegerProcess){
					 mediaInfolist=new ArrayList<Map<String,Object>>();
					  for(Map<String,Object> map:processConfigList){
						  if(map.get("locationId")!=null&&map.get("locationId").toString().equals(wProcess.getLocationId())&&!map.get("processId").toString().equals("tally-event")){
							  dataMap=new HashMap<String,Object>();
							  dataMap.put("deviceId", Integer.parseInt(map.get("deviceId").toString()));
							  dataMap.put("channelId",Integer.parseInt(map.get("channelId").toString()));
							  dataMap.put("from",wProcess.getStartTime().getTime());
							  dataMap.put("to",wProcess.getEndTime().getTime());
							  mediaInfolist.add(dataMap);
						  }
					  }
					  megerMediaInfolist.add(mediaInfolist);
				 }
			 }
		 }
		 //生成合并视频任务
		 if(megerMediaInfolist!=null&&hasMegerProcess&&megerMediaInfolist.size()>0){
			 
		     wvTaskInfo=new WvTaskInfo();
			 wvTaskInfo.setTaskUuid(wvTaskInfo.getUUID());
			 wvTaskInfo.setType(EWvTaskInfo.type_2.getKey());
			 wvTaskInfo.setFpalletId(wvPallet.getPalletId());
			 wvTaskInfo.setFpalletUuid(wvPallet.getPalletUuid());
			 wvTaskInfo.setVideoStatus(EWvTaskInfo.videoStatus_1.getKey());
			 wvTaskInfo.setCreateTime(new Date());
			 wvTaskInfo.setLastCheckTime(new Date());
			 wvTaskInfo.setMedioInfo(JSON.toJSONString(megerMediaInfolist));
			 this.wvTaskInfoService.add(wvTaskInfo);
		 }
	}
	
	/**
	 * 检查用户是否登录 
	 * @param map
	 * @param model
	 * @return
	 */
	public void checkUserIsLoginInfo(Map<String,Object> map){
		String _token=map.get("accessToken")==null?"":map.get("accessToken").toString().trim();
		if(_token.equals("")){
			 throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供accessToken信息！");
		}
		Map<String,Object> newMap=new HashMap<String,Object>();
		newMap.put("accessToken", _token);
		SysAccount acc=new SysAccount();
		acc.setObjMap(newMap);
		this.sysAccountService.updateCheckIsLoginByToken(acc);
	}
	
	
	/**
	 * 检查托盘数据信息
	 * @param map
	 * @param model
	 * @return
	 */
	public void checkWvPalletInfo(Map<String,Object> map,WvPallet model){
		  if(map.get("palletId")==null||StringUtils.isEmpty(map.get("palletId").toString())||map.get("palletId").toString().equals("null")){
			  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供托盘编号（字段：palletId）！");
		  }
		  model.setPalletId(map.get("palletId").toString());
		  model.setUrlStatus(EWvPallet.urlStatus_0.getKey());//未生成
		  //检查托盘palletId不能重复
		  JhCnd cnd=new JhCnd();
		  cnd.andEquals("palletId");
		  model.lnkCnd(cnd);
		  List<Map<String,Object>> list=this.queryMapList(model);
		  if(list!=null&&list.size()>0){
			  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"您提供的托盘编号已存在，不允许重复提交（字段：palletId）！");
		  }
	}
	/**
	 * 检查产品信息
	 * @param map
	 * @param model
	 * @return
	 */
	public void checkWvProductInfo(Map<String,Object> map,List<WvProduct> pList,WvPallet model,String _locationId){
		
		  if(map.get("batchId")==null||StringUtils.isEmpty(map.get("batchId").toString())||map.get("batchId").toString().equals("null")){
			  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供批次编号信息（字段：batchId）！");
		  }
		  if(map.get("spdList")==null){
			  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供订单集合信息（字段：spdList）！");
		  }
		  List<Map<String,Object>>   spdList=(List<Map<String,Object>>)map.get("spdList");
		  WvProduct wvProduc;
		  DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
		  if(spdList==null||spdList.size()<=0){
			  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供订单集合信息,只少提供一项产品信息（字段：spdList）！");
		  }
		  Date date = null;  
		  for(Map<String,Object> tempMap:spdList){
			  wvProduc=new WvProduct();
			  if(tempMap.get("spd")==null||StringUtils.isEmpty(tempMap.get("spd").toString())||tempMap.get("spd").toString().equals("null")||tempMap.get("spd").toString().equals("NULL")){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供审批单号信息（字段：spd）！");
			  }
			  if(tempMap.get("orderId")==null||StringUtils.isEmpty(tempMap.get("orderId").toString())||tempMap.get("orderId").toString().equals("null")||tempMap.get("orderId").toString().equals("NULL")){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供采购单号信息（字段：orderId）！");
			  }
			  if(tempMap.get("productId")==null||StringUtils.isEmpty(tempMap.get("productId").toString())||tempMap.get("productId").toString().equals("null")||tempMap.get("productId").toString().equals("NULL")){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供产品编号信息（字段：productId）！");
			  }
			  if(tempMap.get("productStatu")==null||StringUtils.isEmpty(tempMap.get("productStatu").toString())||tempMap.get("productStatu").toString().equals("null")||tempMap.get("productStatu").toString().equals("NULL")){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供产品状态信息（字段：productStatu）！");
			  }
			  if(tempMap.get("productStatu")==null||StringUtils.isEmpty(tempMap.get("productStatu").toString())){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供产品状态信息（字段：productStatu）！");
			  }
			  if(tempMap.get("productStatu").toString().equals("1")){
				  if(tempMap.get("productCheckTime")==null||StringUtils.isEmpty(tempMap.get("productCheckTime").toString())||tempMap.get("productCheckTime").toString().equals("null")||tempMap.get("productCheckTime").toString().equals("NULL")){
					  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供问题产品理货时间信息（字段：productCheckTime）！");
				  }
		      try {
					date = format.parse(tempMap.get("productCheckTime").toString().trim());
				  } catch (ParseException e) {
					throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供正确的问题产品理货时间，时间格式：yyyy-MM-dd HH:dd:mm");
				  } 
		         if(_locationId.equals("")){
		        	 throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"流程环节中未找到理货环节！环节编码：tallying");
		         }else{
		        	 wvProduc.setLocationId(_locationId);
		         }
			  }else if(tempMap.get("productStatu").toString().equals("0")){
				  date=null;
			  }else{
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供正确的产品状态信息（字段：productStatu：0||1）！");
			  }
			  wvProduc.setOrderId(tempMap.get("orderId").toString());
			  wvProduc.setBatchId(map.get("batchId").toString());
			  wvProduc.setSpd(tempMap.get("spd").toString());
			  wvProduc.setStatus(Integer.parseInt(tempMap.get("productStatu").toString()));
			  wvProduc.setCheckTime(date);
			  wvProduc.setProductUuid(model.getUUID());
			  wvProduc.setProductId(tempMap.get("productId").toString());
			  wvProduc.setFpalletId(model.getPalletId());
			  wvProduc.setUrlStatus(EWvProduct.urlStatus_0.getKey());
			  wvProduc.setUploadStatus(EWvProduct.uploadStatus_1.getKey());
			  wvProduc.setFileUploadStatus(EWvProduct.fileUploadStatus_0.getKey());
			  pList.add(wvProduc);
		  }
		
	}
	
	/**
	 * 检查环节业务数据信息
	 * @param map
	 * @param model
	 * @return
	 */
	public void checkWvProcessInfo(Map<String,Object> map,List<WvProcess> vList,WvPallet model){
		  if(map.get("processList")==null){
			  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供流程集合信息（字段：processList）！");
		  }
		 if(map.get("flowId")==null||StringUtils.isEmpty(map.get("flowId").toString())){
			  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供流程流程编码信息（字段：flowId）！");
		 }
		 //查找流程所有环节及位置码
		 
		 
		  List<Map<String,Object>>   spdList=(List<Map<String,Object>>)map.get("processList");
		  List<String> listProcessId=new ArrayList<String>();
		  List<String> listLocationId=new ArrayList<String>();
		  WvProcess mvProcess;
		  DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		  Date startTime = null,endTime=null; 
		  for(Map<String,Object> newMap:spdList){
			  mvProcess=new WvProcess();
			  if(newMap.get("processId")==null||StringUtils.isEmpty(newMap.get("processId").toString())||newMap.get("processId").toString().equals("null")){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供流程环节编号信息（字段：processId）！");
			  }
			  if(newMap.get("startTime")==null||StringUtils.isEmpty(newMap.get("startTime").toString())||newMap.get("startTime").toString().equals("null")){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供流程环节开始时间编号信息（字段：startTime）！");
			  }
			  if(newMap.get("endTime")==null||StringUtils.isEmpty(newMap.get("endTime").toString())||newMap.get("endTime").toString().equals("null")){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供流程环节结束时间编号信息（字段：endTime）！");
			  }
			  if(newMap.get("locationId")==null||StringUtils.isEmpty(newMap.get("locationId").toString())||newMap.get("locationId").toString().equals("null")){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供位置码信息（字段：locationId）！");
			  }
			  
			  mvProcess.setProcessUuid(model.getUUID());
			  mvProcess.setFpalletId(model.getPalletId());
			  mvProcess.setFprocessId(newMap.get("processId").toString());
			    
		      try {
		    	  startTime = format.parse(newMap.get("startTime").toString().trim());
			  } catch (ParseException e) {
				throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供正确的流程环节开始时间，时间格式：yyyy-MM-dd HH:dd:mm");
			  }  
		      try {
		    	  endTime = format.parse(newMap.get("endTime").toString().trim());
			  } catch (ParseException e) {
				throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供正确的流程环节结束时间，时间格式：yyyy-MM-dd HH:dd:mm");
			  }  
		      if(startTime.after(endTime)){
		    	  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供正确的流程环节开始时间， 结束时间必需大于开始时间");
		      }
			  mvProcess.setStartTime(startTime);
			  mvProcess.setEndTime(endTime);
			  mvProcess.setUrlStatus(0);
			  mvProcess.setLocationId(newMap.get("locationId").toString());
			  mvProcess.setUploadStatus(EWvProcess.uploadStatus_1.getKey());
			  mvProcess.setFileUploadStatus(EWvProcess.fileUploadStatus_0.getKey());
			  vList.add(mvProcess);
			  listProcessId.add(newMap.get("processId").toString());
			  listLocationId.add(newMap.get("locationId").toString());
		  }
		  List<Map<String,Object>> mvList=null;
		  JhCnd cnd=new JhCnd();
		  if(listProcessId.size()>0){
			  WvProcessConfig wvModel=new WvProcessConfig();
			  wvModel.setStrList(listProcessId);
			  cnd.reset();
			  cnd.andIn("processId", "strList", listProcessId);
			  wvModel.lnkCnd(cnd);
			  mvList=this.wvProcessConfigService.queryMapListById(wvModel, "queryMapListProcessconfigGroupByProcessId");
			  if(mvList==null || listProcessId.size()!=mvList.size()){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"提供的流程环节编号信息有误！（相关字段：processId）！");
			  } 
			  mvList.clear();
		  }
		  if(listProcessId.size()>0){
			  WvProcessConfig wvModel=new WvProcessConfig();
			  wvModel.setFcode(map.get("flowId").toString());
			  cnd.reset();
			  cnd.andEquals("fcode");
			  cnd.andNotEquals("processId");
			  wvModel.setProcessId("tally-event");
			  wvModel.lnkCnd(cnd);
			  mvList=this.wvProcessConfigService.queryMapListById(wvModel, "queryMapListProcessconfigGroupByProcessId");
			  if(mvList==null || listProcessId.size()!=mvList.size()){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"提供的流程环节数量有误，请检查流程环节信息是否完整！系统共提供"+mvList.size()+"个流程环节，您共提供"+listProcessId.size()+"个流程环节。（相关字段：processId）！");
			  }
			  mvList.clear();
		  }
		  //检验位置位置信息
		  if(listLocationId.size()>0){
			  WvProcessConfig wvModel=new WvProcessConfig();
			  wvModel.setFcode(map.get("flowId").toString());
			  cnd.reset();
			  cnd.andEquals("fcode");
			  cnd.andNotEquals("processId");
			  wvModel.setProcessId("tally-event");
			  wvModel.setStrList(listLocationId);
			  cnd.andIn("locationId", "strList", listLocationId);
			  wvModel.setJhCnd(cnd);
			  mvList=this.wvProcessConfigService.queryMapListById(wvModel, "queryMapListProcessconfigGroupByLocationId");
			  if(mvList==null || listLocationId.size()!=mvList.size()){
				  throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"提供的位置码信息有误！请检查位置码信息是否完整！系统查询到"+mvList.size()+"个位置码信息，您共提供"+listLocationId.size()+"个位置码信息。（相关字段：locationId）！");
			  }
			  mvList.clear();
		  }
	}
	@Override
	public void updateWvPalletUrlLink(WvPallet model) {
		Map<String,Object> map=model.getObjMap();
		if(map==null){
			throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请求参数有误 ！");
		}
		if(map.get("palletUuid")==null||StringUtils.isEmpty(map.get("palletUuid").toString())){
			throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供产品UUID名称！");
		}
		model.setPalletUuid(map.get("palletUuid").toString());
		
		if(map.get("urlLink")==null||StringUtils.isEmpty(map.get("urlLink").toString())){
			throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供视频地址信息名称！");
		}
		model.setUrlLink(map.get("urlLink").toString());
		
		 
		JhCnd cnd = new JhCnd();
		cnd.andEquals("palletUuid");
		model.lnkCnd(cnd);
		JhUpdate update=new JhUpdate();
		update.add("urlLink").add("urlStatus").add("fileUploadStatus");
		model.setUrlStatus(EWvPallet.urlStatus_1.getKey());
		model.setFileUploadStatus(EWvPallet.fileUploadStatus_2.getKey());
		model.setJhUpdate(update);
		this.updateSame(model);
		
		//保存视频任务生成
		WvUploadTaskInfo wvTaskInfo=new WvUploadTaskInfo();
		wvTaskInfo.setTaskUuid(model.getUUID());
		wvTaskInfo.setCreateTime(new Date());
		wvTaskInfo.setTaskType(EWvUploadTaskInfo.taskType_7.getKey());
		wvTaskInfo.setWorkUuid(model.getPalletUuid());
		wvTaskInfo.setTaskLevel(EWvUploadTaskInfo.taskType_7.getKey());
		this.wvUploadTaskInfoService.add(wvTaskInfo);
		
	}

	@Override
	public void listAllWvPallet(WvPallet model) {
		JhCnd cnd=new JhCnd();
		cnd.append("1=1");
		if(StringUtils.isNotEmpty(model.getPalletId())){
			cnd.andEquals("palletId");
		}
		Map<String,String> map=model.getStrMap();
		if(model.getStrMap()!=null){
			if(map.get("start")!=null&&!map.get("start").toString().trim().equals("")&&map.get("end")!=null&&!map.get("end").toString().trim().equals("")){
				cnd.append(" and (DATE_FORMAT(create_time, '%Y-%m-%d')>='"+map.get("start").toString()+"' and DATE_FORMAT(create_time, '%Y-%m-%d')<='"+map.get("end").toString()+"')");
			}
			if(map.get("start")!=null&&!map.get("start").toString().trim().equals("")&&(map.get("end")==null||map.get("end").toString().trim().equals(""))){
				cnd.append(" and DATE_FORMAT(create_time, '%Y-%m-%d')>='"+map.get("start").toString()+"'");
			}
			if(map.get("end")!=null&&!map.get("end").toString().trim().equals("")&&(map.get("start")==null||map.get("start").toString().trim().equals(""))){
				cnd.append(" and DATE_FORMAT(create_time, '%Y-%m-%d')<='"+map.get("end").toString()+"'");
			}
		}
		cnd.orderBy("createTime", ORDER.DESC);
		model.setJhCnd(cnd);
		List<Map<String,Object>> list=this.queryMapListById(model, "queryMapListAllWvPallet");
		model.setMapList(list);
	}

	public void listAllWvPalletTJ(WvPallet model){
		List<Map<String,Object>> list=this.queryMapListById(model, "queryMapListAllWvPalletTJ");
		model.setMapList(list);
	}
	
	public void updateStopGenerateVideo(WvPallet model){
		if(StringUtils.isEmpty(model.getPalletUuid())){
			throw new JingHaoCustomerException("提供托盘UUID信息！");
		}
		WvTaskInfo wvTask =new WvTaskInfo();
		JhCnd cnd=new JhCnd();
		cnd.reset();
		cnd.andEquals("fpalletUuid");
		wvTask.setFpalletUuid(model.getPalletUuid());
		cnd.andEquals("type");
		wvTask.setType(EWvTaskInfo.type_2.getKey());
		wvTask.setJhCnd(cnd);
		this.wvTaskInfoService.deleteSame(wvTask);
		
		Map<String,Object> dataMap=new HashMap<String,Object>();
		dataMap.put("urlStatus", EWvProduct.urlStatus_0.getKey());
		List<Map<String,Object>> datalist=new ArrayList<Map<String,Object>>();
		datalist.add(dataMap);
		model.setMapList(datalist);
	}
	@Override
	public void updateGenerateVedio(WvPallet model) {
		if(StringUtils.isEmpty(model.getPalletUuid())){
			throw new JingHaoCustomerException("提供托盘UUID信息！");
		}
		WvPallet wvPallet=this.get(model);
		if(wvPallet==null){
			throw new JingHaoCustomerException("未找到托盘信息！");
		}
		this.synchronousReSetPallet(wvPallet);
		String medioInfo=this.getVedioMediaInfo(wvPallet);
		if(medioInfo!=null&&!medioInfo.trim().equals("")){
			Map<String,Object> map=new HashMap<String,Object>();
			this.updateGenerateVideoTask(wvPallet,medioInfo,map);
			List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
			list.add(map);
			model.setMapList(list);
		}else{
			throw new JingHaoCustomerException("未找到对应合并环节信息！");
		}
	}
	
	public void updateGenerateVedioTemp(WvPallet model) { 
		if(StringUtils.isEmpty(model.getPalletUuid())){
			throw new JingHaoCustomerException("提供托盘UUID信息！");
		}
		WvPallet wvPallet=this.get(model);
		if(wvPallet==null){
			throw new JingHaoCustomerException("未找到托盘信息！");
		}
	//	this.synchronousReSetPallet(wvPallet);
		String medioInfo=this.getVedioMediaInfo(wvPallet);
		if(medioInfo!=null&&!medioInfo.trim().equals("")){
			WvTaskInfo wvTask=new WvTaskInfo();
			wvTask.setTaskUuid(model.getUUID());
			wvTask.setFpalletUuid(wvPallet.getPalletUuid());
			wvTask.setFpalletId(wvPallet.getPalletId());
			wvTask.setCreateTime(new Date());
			wvTask.setMedioInfo(medioInfo);
			wvTask.setVideoStatus(EWvTaskInfo.videoStatus_1.getKey());
			wvTask.setLastCheckTime(new Date());
			wvTask.setType(EWvTaskInfo.type_2.getKey());
			this.wvTaskInfoService.add(wvTask);
		}else{
			throw new JingHaoCustomerException("未找到对应合并环节信息！");
		}
	}
	@Override
	public void updateReSetAllGenerateVedio(WvPallet model) {
		model.setPage(null);
		 List<WvPallet> list=this.queryModelList(model);
		 for(WvPallet newModel:list){
			 this.updateGenerateVedioTemp(newModel);
		 }
		 if(list!=null){
			 list.clear();
			 list=null;
		 }
	}

	public void synchronousReSetPallet(WvPallet wvPallet){
		WvCloudAccessConfig model=new WvCloudAccessConfig();
		//第一步：查询是否配置云段接口及云平台验证
		Map<String,Object> dateInfo=this.wvPublicSynchronousService.cloudLogin(model);
		model=(WvCloudAccessConfig)dateInfo.get("wvCloudAccessConfig");
		JhHttpClientUtil hd = new JhHttpClientUtil();
		Map<String,String> map=new HashMap<String,String>();
		Object obj=dateInfo.get("loginInfo");
		Map<String,Object> loginInfo=(Map<String,Object>)obj;
		map.put("accessTokenData", JSON.toJSONString(loginInfo));
		Map<String,Object> dataMap=null;
		if(wvPallet!=null){
			dataMap=new HashMap<String,Object>();
			dataMap.put("palletUuid", wvPallet.getPalletUuid());
			dataMap.put("fileName", wvPallet.getPalletId()+"combine");
			map.put("jhPublicData", JSON.toJSONString(dataMap));
			String dtUrl="app/ctws/public/syn/updateReSetPalletFile";
			String httpUrl=model.getAddress();
			if(httpUrl.substring(httpUrl.length()-1, httpUrl.length()).equals("/")){
				httpUrl=model.getAddress()+""+dtUrl;
			}else{
				httpUrl=model.getAddress()+"/"+dtUrl; 
			}
			String msg= hd.post(httpUrl, map);
			this.wvPublicSynchronousService.checkResult(msg);
		} 
	}
	 
	public void updateGenerateVideoTask(WvPallet model,String medioInfo,Map<String,Object> dataMap){
		
		WvAccessConfig wvAccessConfig=this.wvAccessConfigService.getWvAccessConfigInfo();
		String userName=wvAccessConfig.getUsername();
		String password=wvAccessConfig.getPassword();
		String dtUrl=wvAccessConfig.getBucket();
		String httpUrl=wvAccessConfig.getAddress();
		if(httpUrl.substring(httpUrl.length()-1, httpUrl.length()).equals("/")){
			httpUrl=wvAccessConfig.getAddress()+""+dtUrl;
		}else{
			httpUrl=wvAccessConfig.getAddress()+"/"+dtUrl;
		}
		int isSuccess=0;
		String url="";
		WvTaskInfo wvTask=new WvTaskInfo();
		//第一步：登录 
		String sessionKey=this.wvAccessConfigService.vmsLogin(userName,password,httpUrl);
		String concatenateRequestId=null;
		Map<String,Object> videoMap=this.wvAccessConfigService.vmsRequestconcatenatevideo(httpUrl,sessionKey,medioInfo);
		if(videoMap.get("result")!=null&&videoMap.get("result").toString().equals("ok")){
			concatenateRequestId=videoMap.get("concatenate-request-id").toString();
        }else{
        	concatenateRequestId=null;
        }
		
		Map<String,Object> resultMap=null,fileMap=null;
		//第三步：获取视频生成状态
		resultMap=this.wvAccessConfigService.vmsCheckconcatenatevideostatus(httpUrl,sessionKey, concatenateRequestId);
		if(concatenateRequestId!=null&&!concatenateRequestId.trim().equals("")){
			if(resultMap!=null&&resultMap.get("result")!=null&&resultMap.get("result").toString().equals("ok")){
				if(resultMap.get("status")!=null&&resultMap.get("status").toString().equals("COMPLETED")){
					if(resultMap.get("file")!=null){
						fileMap=(Map<String,Object>)resultMap.get("file");
						if(fileMap.get("url")!=null){
							isSuccess=2;
							url=fileMap.get("url").toString();
						}else{
							wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
							wvTask.setErrorInfo(JSON.toJSONString(resultMap));
							//未知错误信息
							this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
						}
					}else{
						wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
						wvTask.setErrorInfo(JSON.toJSONString(resultMap));
						//未知错误信息
						this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
					}
					
				}else if(resultMap.get("status")!=null&&resultMap.get("status").toString().equals("IN_PROGRESS")){
					if(resultMap.get("progress")!=null){
						isSuccess=1;
						wvTask.setProgress(Integer.parseInt(resultMap.get("progress").toString()));
						wvTask.setVideoStatus(EWvTaskInfo.videoStatus_2.getKey());
					}else{
						wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
						wvTask.setErrorInfo(JSON.toJSONString(resultMap));
						//未知错误信息
						this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
					}
				}else{
					wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
					wvTask.setErrorInfo(JSON.toJSONString(resultMap));
					//未知错误信息
					this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
				}
			}else if(resultMap!=null&&resultMap.get("result")!=null&&resultMap.get("result").toString().equals("error")){
				wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
				wvTask.setErrorInfo(JSON.toJSONString(resultMap));
			}else{
				wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
				wvTask.setErrorInfo(JSON.toJSONString(resultMap));
				//未知错误信息
				this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
			}
		}else{
			wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
			wvTask.setErrorInfo(JSON.toJSONString(videoMap));
        	this.logger.info("自动生成视频异常信息（vmsRequestconcatenatevideo）：时间："+new Date()+",mediaInfo:"+medioInfo+",result:"+JSON.toJSONString(videoMap));
		}
		JhUpdate updateSet=new JhUpdate();
		JhCnd cnd=new JhCnd();
		WvPallet wvPallet=null;
		//第四步：更新任务信息表
		if(isSuccess==0){//生成失败
			throw new JingHaoCustomerException("生成视频发生错误！错误信息："+wvTask.getErrorInfo());
			
		//	dataMap.put("urlStatus", EWvPallet.urlStatus_0.getKey());
		//	dataMap.put("videoStatus", EWvTaskInfo.videoStatus_9.getKey());
		//	dataMap.put("errorInfo", wvTask.getErrorInfo());
			
		}else if(isSuccess==1){ //生成中
			cnd.reset();
			updateSet.add("urlStatus").add("fileUploadStatus");
			wvPallet=new WvPallet();
			wvPallet.setPalletUuid(model.getPalletUuid());
			wvPallet.setUrlStatus(EWvPallet.urlStatus_0.getKey());
			wvPallet.setFileUploadStatus(EWvPallet.fileUploadStatus_0.getKey());
			cnd.andEquals("palletUuid");
			wvPallet.setJhCnd(cnd);
			wvPallet.setUpdateSet(updateSet);
			this.wvPalletService.updateSame(wvPallet);
			
			
			cnd.reset();
			cnd.andEquals("fpalletUuid");
			wvTask.setFpalletUuid(model.getPalletUuid());
			cnd.andEquals("type");
			wvTask.setType(EWvTaskInfo.type_2.getKey());
			wvTask.setJhCnd(cnd);
			this.wvTaskInfoService.deleteSame(wvTask);
			
			wvTask.setTaskUuid(model.getUUID());
			wvTask.setFpalletUuid(model.getPalletUuid());
			wvTask.setFpalletId(model.getPalletId());
			wvTask.setCreateTime(new Date());
			wvTask.setMedioInfo(medioInfo);
			wvTask.setVideoStatus(EWvTaskInfo.videoStatus_2.getKey());
			wvTask.setLastCheckTime(new Date());
			wvTask.setType(EWvTaskInfo.type_2.getKey());
			wvTask.setRequestId(concatenateRequestId);
			this.wvTaskInfoService.add(wvTask);
			
			
			dataMap.put("urlStatus", EWvPallet.urlStatus_0.getKey());
			dataMap.put("videoStatus", EWvTaskInfo.videoStatus_2.getKey());
			dataMap.put("progress", wvTask.getProgress());
			
		}else if(isSuccess==2){//生成成功
			cnd.reset();
			//合并环节任务
			updateSet.add("urlStatus").add("urlLink").add("fileUploadStatus");
			wvPallet=new WvPallet();
			wvPallet.setPalletUuid(model.getPalletUuid());
			wvPallet.setUrlLink(url);
			wvPallet.setUrlStatus(EWvPallet.urlStatus_1.getKey());
			wvPallet.setFileUploadStatus(EWvPallet.fileUploadStatus_1.getKey());
			cnd.andEquals("palletUuid");
			wvPallet.setJhCnd(cnd);
			wvPallet.setUpdateSet(updateSet);
			this.wvPalletService.updateSame(wvPallet);
			
			cnd.reset();
			cnd.andEquals("fpalletUuid");
			wvTask.setJhCnd(cnd);
			wvTask.setFpalletUuid(model.getPalletUuid());
			cnd.andEquals("type");
			wvTask.setType(EWvTaskInfo.type_2.getKey());
			this.wvTaskInfoService.deleteSame(wvTask);
			
			dataMap.put("urlStatus", EWvPallet.urlStatus_1.getKey());
			dataMap.put("urlLink", wvPallet.getUrlLink());
		}
		 
	}
	
	public String getVedioMediaInfo(WvPallet wvPallet){
		JhCnd cnd=new JhCnd();
		//获取合并配置信息
		WvProcessMergeConfig wvProcessMergeConfig=new WvProcessMergeConfig();
		cnd.reset();
		cnd.andEquals("flowCode");
		cnd.orderBy("sort", ORDER.ASC);
		wvProcessMergeConfig.setFlowCode(wvPallet.getFlowCode());
		wvProcessMergeConfig.setJhCnd(cnd);
		List<String> strList=new ArrayList<String>();
		List<WvProcessMergeConfig> listWvProcessMergeConfig=this.wvProcessMergeConfigService.queryModelList(wvProcessMergeConfig);
		if(listWvProcessMergeConfig.isEmpty()){
			throw new JingHaoCustomerException(EJhTwsCode.TWS10002.getCode(),"请配置环节合并信息！");
		}
		for(WvProcessMergeConfig tempModel:listWvProcessMergeConfig){
			strList.add(tempModel.getProcessCode());
		}
		//B：查询流程对应的所有环节数据 fpalletId
		WvProcess  wvProcess=new WvProcess();
		wvProcess.setStrList(strList);
		cnd.reset();
		cnd.append(" 1=1 and p.fpallet_Id='"+wvPallet.getPalletId()+"' and pc.fcode='"+wvPallet.getFlowCode()+"'  and pc.process_id<>'tally-event' ");
		cnd.andIn("fprocessId", "strList", strList);
	//	wvProcess.setFpalletId(wvPallet.getPalletId());
		wvProcess.lnkCnd(cnd);
		wvProcess.setPage(null);
		List<Map<String,Object>> listProcess=this.wvProcessService.queryMapListById(wvProcess,"queryWvProcessAndCameraByTask");
		if(listProcess==null||listProcess.size()<=0){
			throw new JingHaoCustomerException(EJhTwsCode.TWS10002.getCode(),"未找到对应合并环节信息！");
		}
		List<Map<String,Object>> bList=null;
		List<List<Map<String,Object>>> aList=new ArrayList<List<Map<String,Object>>>();
		Date fromDate,toDate;
		Map<String,Object> totalDataMap=null;
		for(String strCode:strList){
			bList=new ArrayList<Map<String,Object>>();
			for(Map<String,Object> map:listProcess){
				if(map.get("fprocessId")!=null&&map.get("fprocessId").toString().equals(strCode)){
					fromDate=(Date)map.get("startTime");
					toDate=(Date)map.get("endTime");
					totalDataMap=new HashMap<String,Object>();
					totalDataMap.put("deviceId", Integer.parseInt(map.get("deviceId").toString()));
					totalDataMap.put("channelId", Integer.parseInt(map.get("channelId").toString()));
					totalDataMap.put("from", fromDate.getTime());
					totalDataMap.put("to", toDate.getTime());
					bList.add(totalDataMap);
				}
			}
			if(bList.size()>0){
				aList.add(bList);
			}
		}
		return JSON.toJSONString(aList);
	}
	//==================定制内容结束======================
}
